//
//  YcjxyybVC.swift
//  Auscultation
//
//  Created by 来 on 2020/12/23.
//

import UIKit

class YcjxyybVC: BaseVC {
    
    var collectionView: UICollectionView!
    
    var keyWord: String = ""
    var sx_state: Int = 0
    
    var dataArray: [Any] = (UserDefaults.standard.array(forKey: LGF_BD_WAV_ARRAY) ?? []).reversed()

    override func viewDidLoad() {
        super.viewDidLoad()

        initUI()
        NotificationCenter.default.addObserver(self, selector: #selector(YcjxyybVC.BdhzVCNoti(_:)), name: NSNotification.Name(rawValue: "BdhzVCNoti"), object: nil)
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "YcjxyybCellPlayerStop"), object: nil)
    }
    
    @objc func s_sx(_ sender: UITapGestureRecognizer) {
        SxV().showIn(self.view, ["类型"], ["类型": ["心音样本", "文件下载"]], [self.sx_state]) { [weak self] (sxv, name, state) in
            self?.sx_state = state.first ?? 0
            self?.collectionView.reloadData()
        }
    }
    
}

extension YcjxyybVC: UITextFieldDelegate {
    func textFieldDidEndEditing(_ textField: UITextField) {
        keyWord = textField.text ?? ""
        collectionView.reloadData()
    }
}

extension YcjxyybVC: UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource, UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "YcjxyybCellPlayerStop"), object: nil)
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize  {
        let datas = getFDatas()
        if let data = datas[indexPath.item] as? [String: Any] {
            let type = (data["type"] as? String) ?? ""
            if type == "已上传" {
                return CGSize.init(width: UIDevice.lgf_ScreenW, height: 130)
            }
        }
        return CGSize.init(width: UIDevice.lgf_ScreenW, height: 170)
    }
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return getFDatas().count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.lgf_DequeueReusableCell(with: YcjxyybCell.self, for: indexPath)
        cell.tag = indexPath.item
        let datas = getFDatas()
        if let data = datas[indexPath.item] as? [String: Any] {
            cell.data = data
            cell.tzzx.text = (data["name"] as? String) ?? ""
            cell.cjsj.text = "创建时间：" + (((data["time"] as? String) ?? "0").lgf_TimeStampToDate().lgf_TimeStr("yyyy-MM-dd HH:mm:ss"))
            cell.url = (data["wav_path"] as? String) ?? ""
            cell.zt.text = (data["type"] as? String) ?? ""
            cell.initPlay()
            cell.allTime = "00:00"
            cell.play_time.text = "00:00/" + cell.allTime
            let type = (data["type"] as? String) ?? ""
            if type != "已上传" {
                if data.keys.contains("patient") {
                    cell.fx.text = "上传"
                } else {
                    cell.fx.text = "绑定患者"
                }
            }
        }
        cell.delegate = self
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if let data = dataArray[indexPath.item] as? [String: Any] {
            let vc = BdjlxqVC()
            vc.data = data
            vc.delegate = self
            self.navigationController?.show(vc, sender: self)
        }
    }
    
    func getFDatas() -> [Any] {
        let datas = dataArray.filter({ (dict) -> Bool in
            if self.sx_state != 0 {
                if let data = dict as? [String: Any] {
                    let state = (data["state"] as? String) ?? ""
                    return (state == self.sx_state.description)
                }
            }
            return true
        }).filter({ (dict) -> Bool in
            if self.keyWord.count > 0 {
                if let data = dict as? [String: Any] {
                    let name = (data["name"] as? String) ?? ""
                    return (name.contains(self.keyWord))
                }
            }
            return true
        })
        return datas
    }
}

extension YcjxyybVC: YcjxyybCellDelegate {
    func selectBD(_ cell: YcjxyybCell, _ data: [String: Any]) {
        if data.keys.contains("patient") {
            let vc = YbscVC()
            vc.data = data
            self.navigationController?.show(vc, sender: self)
        } else {
            let vc = BdhzVC()
            vc.data = data
            self.navigationController?.show(vc, sender: self)
        }
    }
}

extension YcjxyybVC {
    @objc func BdhzVCNoti(_ sender: Notification) {
        let rdataArray: [Any] = UserDefaults.standard.array(forKey: LGF_BD_WAV_ARRAY) ?? []
        self.dataArray = rdataArray.reversed()
        self.collectionView.reloadData()
    }
}

extension YcjxyybVC: BdjlxqVCDelegate {
    func deleteBdjlxq(_ data: [String : Any]) {
        let rdataArray: [Any] = (UserDefaults.standard.array(forKey: LGF_BD_WAV_ARRAY) ?? [])
        self.dataArray = rdataArray.reversed()
        self.collectionView.reloadData()
    }
}

